<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="loginForm.mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true ,trigger: 'onChange' ,message: '请填写手机号', pattern: /^1[3-9]\d{9}$/ }]"
      />
      <van-field
        v-model="loginForm.code"
        required
        type="password"
        label="登录密码"
        placeholder="密码"
        :rules="[{ required: true ,trigger: 'onChange' , message: '请填写密码',pattern:/^\d{6}$/  }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit" :loading="isLoading" :disabled="isLoading" loading-text="加载中..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { MyNotify } from '@/utils/Notify'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      loginForm: {
        mobile: '13543522334',
        code: '246810'
      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefreshToken']),
    async onSubmit () {
      this.isLoading = true
      try {
        const res = await loginAPI(this.loginForm)
        console.log(res.data.data)
        const { token, refresh_token } = res.data.data
        this.setToken(token)
        this.setRefreshToken(refresh_token)
        MyNotify({ type: 'success', message: '登录成功' })
        this.isLoading = false
        if (this.$route.query.code === '401') {
          this.$router.back()
        } else {
          this.$router.replace({
            path: '/layout'
          })
        }
      } catch (error) {
        this.isLoading = false
        MyNotify({ type: 'danger', message: '登录失败' })
      }
    }
  }
}
</script>

<style lang='less' scoped>
</style>
